package com.sport.common.word;

import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy;
import com.jeesite.common.codec.EncodeUtils;
import com.sport.model.excel.SportMemberEnrollExport;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xwpf.usermodel.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Word {

    public static void mergeWordDocuments(File[] files,  HttpServletResponse response, String fileName) {
        try {
            XWPFDocument mergedDocument = new XWPFDocument();
            response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document; charset=UTF-8");
            response.addHeader("Content-Disposition", "attachment; filename*=utf-8''" + URLEncoder.encode(fileName, "UTF-8"));

            ServletOutputStream outputStream = response.getOutputStream();
            for (File document : files) {
                FileInputStream fis = new FileInputStream(document);
                XWPFDocument doc = new XWPFDocument(fis);

                copyBodyElements(doc.getBodyElements(), mergedDocument);

                fis.close();
                doc.close();
            }


            mergedDocument.write(outputStream);
            mergedDocument.close();

            System.out.println("合并完成并导出为文件：" );
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void copyBodyElements(List<IBodyElement> sourceElements, XWPFDocument targetDocument) {
        try {
            for (IBodyElement element : sourceElements) {
                if (element instanceof XWPFParagraph) {
                    XWPFParagraph sourceParagraph = (XWPFParagraph) element;
                    XWPFParagraph targetParagraph = targetDocument.createParagraph();

                    // 复制段落属性
                    targetParagraph.getCTP().setPPr(sourceParagraph.getCTP().getPPr());

                    // 复制段落文本和格式
                    for (IRunElement runElement : sourceParagraph.getIRuns()) {
                        if (runElement instanceof XWPFRun) {
                            XWPFRun sourceRun = (XWPFRun) runElement;
                            XWPFRun targetRun = targetParagraph.createRun();
                            targetRun.setText(sourceRun.text());

                            // 复制字体格式
                            targetRun.getCTR().setRPr(sourceRun.getCTR().getRPr());
                        }
                    }
                } else if (element instanceof XWPFTable) {
                    XWPFTable sourceTable = (XWPFTable) element;
                    XWPFTable targetTable = targetDocument.createTable(sourceTable.getRows().size(), getMaxColumnCount(sourceTable));

                    // 复制表格内容
                    for (int rowIndex = 0; rowIndex < sourceTable.getRows().size(); rowIndex++) {
                        XWPFTableRow sourceRow = sourceTable.getRow(rowIndex);
                        XWPFTableRow targetRow = targetTable.getRow(rowIndex);

                        for (int cellIndex = 0; cellIndex < sourceRow.getTableCells().size(); cellIndex++) {
                            XWPFTableCell sourceCell = sourceRow.getCell(cellIndex);
                            XWPFTableCell targetCell = targetRow.getCell(cellIndex);

                            // 复制单元格属性
                            targetCell.getCTTc().setTcPr(sourceCell.getCTTc().getTcPr());

                            // 复制单元格内容和格式
                            copyBodyElements(sourceCell.getBodyElements(), targetCell);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static int getMaxColumnCount(XWPFTable table) {
        int maxColumnCount = 0;

        for (XWPFTableRow row : table.getRows()) {
            int columnCount = row.getTableCells().size();
            if (columnCount > maxColumnCount) {
                maxColumnCount = columnCount;
            }
        }

        return maxColumnCount;
    }
    private static void copyBodyElements(List<IBodyElement> sourceElements, XWPFTableCell targetCell) {
        for (IBodyElement element : sourceElements) {
            try {
                if (element instanceof XWPFParagraph) {
                    XWPFParagraph sourceParagraph = (XWPFParagraph) element;
                    XWPFParagraph targetParagraph = targetCell.addParagraph();

                    // 复制段落属性
                    targetParagraph.getCTP().setPPr(sourceParagraph.getCTP().getPPr());

                    // 复制段落文本和格式
                    for (IRunElement runElement : sourceParagraph.getIRuns()) {
                        if (runElement instanceof XWPFRun) {
                            XWPFRun sourceRun = (XWPFRun) runElement;
                            XWPFRun targetRun = targetParagraph.createRun();
                            targetRun.setText(sourceRun.text());

                            // 复制字体格式
                            targetRun.getCTR().setRPr(sourceRun.getCTR().getRPr());
                        }
                    }
                } else if (element instanceof XWPFTable) {
                    XWPFTable sourceTable = (XWPFTable) element;
                    XWPFTable targetTable = targetCell.getTableRow().getTable();

                    // 复制表格内容
                    for (int rowIndex = 0; rowIndex < sourceTable.getRows().size(); rowIndex++) {
                        XWPFTableRow sourceRow = sourceTable.getRow(rowIndex);
                        XWPFTableRow targetRow = targetTable.createRow();

                        for (int cellIndex = 0; cellIndex < sourceRow.getTableCells().size(); cellIndex++) {
                            XWPFTableCell sourceCell = sourceRow.getCell(cellIndex);
                            XWPFTableCell targetCell1 = targetRow.getCell(cellIndex);

                            // 复制单元格属性
                            targetCell1.getCTTc().setTcPr(sourceCell.getCTTc().getTcPr());

                            // 复制单元格内容和格式
                            copyBodyElements(sourceCell.getBodyElements(), targetCell);
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

        /**
         * 根据本地文件流生成word
         *
         */


        public void mergeTempFiles(File tempFolder, HttpServletResponse response, String fileName) {

                File[] files = tempFolder.listFiles();
                mergeWordDocuments(files,response,fileName);
//                if(files!=null&&files.length>0) {
//                    response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document; charset=UTF-8");
//                    response.addHeader("Content-Disposition", "attachment; filename*=utf-8''" + URLEncoder.encode(fileName, "UTF-8"));
//
//                    ServletOutputStream outputStream = response.getOutputStream();
//                    FileInputStream fis;
//                    byte[] buffer= new byte[4096];
//                    int bytesRead;
//                    for (File file : files) {
//                        fis=new FileInputStream(file);
//                        while((bytesRead=fis.read(buffer))!=-1){
//                            outputStream.write(buffer,0,bytesRead);
//                        }
//                        fis.close();
//                    }
//                    outputStream.flush();
//                    outputStream.close();
//
//                }
//            } catch (IOException e) {
//                throw new RuntimeException(e);
//            }

        }



        public File createTempFolder() {
            String tempFoldPath = System.getProperty("java.io.tmpddir");
            File tempFolder = new File(tempFoldPath, "word-export");
            if(!tempFolder.exists()){
                tempFolder.mkdirs();
            }
            return tempFolder;
        }



}
